package com.zmn.oms.admin.controller.common;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerDetailInfoDRO;
import com.zmn.base.engineer.common.dro.supervisor.SupervisorDetailDRO;
import com.zmn.base.engineer.common.query.supervisor.SupervisorInfoQuery;
import com.zmn.base.engineer.dubbo.interfaces.foreign.EngineerListRemoteService;
import com.zmn.base.engineer.dubbo.interfaces.supervisor.EngineerSupervisorListRemoteService;
import com.zmn.biz.engineer.common.dro.engineer.basic.ThinkEngineerDRO;
import com.zmn.biz.engineer.common.query.engineer.ThinkEngineerQuery;
import com.zmn.biz.engineer.dubbo.interfaces.basic.EngineerBasicListRemoteService;
import com.zmn.common.dto2.Option;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.consts.GlobalConsts;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.mcc.common.dto.organize.OrganizeDRO;
import com.zmn.mcc.common.dto.staff.StaffDRO;
import com.zmn.mcc.common.dto.staff.StaffSimpleQueryDIO;
import com.zmn.mcc.dubbo.interfaces.staff.StaffListRemoteService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.common.vo.KVDict;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类描述：员工查询
 * @author liuying
 * @date 2018/11/21 15:36
 */
@RestController
@RequestMapping("/staff")
public class StaffController extends OmsBaseController {

    @DubboReference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerListRemoteService engineerListRemoteService;

   // @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
   // private BaseInfoListRemoteService baseInfoListRemoteService;

   // @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    //private EngineerPermissionListRemoteService engineerPermissionListRemoteService;

    @DubboReference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerBasicListRemoteService engineerBasicListRemoteService;

    @DubboReference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerSupervisorListRemoteService engineerSupervisorListRemoteService;

    @DubboReference(version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION, check = false)
    private StaffListRemoteService staffListRemoteService;


    /**
     * 查询员工列表
     * @return
     */
    @GetMapping(value = "dept/staff/list")
    public ResultDTO deptStaffList(@RequestParam Integer deptId,
                                   @RequestParam(value = "text", required = false) String text) {
        StaffSimpleQueryDIO query = new StaffSimpleQueryDIO();
        query.setDeptIds(Lists.newArrayList(deptId));
        query.setKeyword(text);
        ResponseDTO<List<StaffDRO>> staffResponseDTO = staffListRemoteService.listStaffBySimpleQueryDIO(query);
        if (staffResponseDTO.getData() == null) {
            return ResultDTO.fail("list is empty");
        }

        List<KVDict<?>> list = staffResponseDTO.getData().stream().map((item) -> {
            String statusName = Objects.equals(item.getStatus(), GlobalConsts.NO) ? "(离职)" : "";
            String staffName = item.getRealName() + statusName;
            return KVDict.builder().value(item.getStaffId()).text(staffName).ext1(MobileUtil.formatHideTel(item.getMobile())).build();
        }).collect(Collectors.toList());

        return ResultDTO.success(list);
    }

    /**
     * 查询员工列表(操作员)
     * @return
     */
    @GetMapping(value = "staff/company/list")
    public ResultDTO companyStaffList(@RequestParam(value = "companyId", required = false) Integer companyId,
                                      @RequestParam(value = "text") String text,
                                      @RequestParam(value = "status", required = false) Integer status) {

        LoginStaff loginStaff = getCurrentStaff();
        ResponseDTO<OrganizeDRO> organDROResponseDTO = organizeListRemoteService.getByKey(loginStaff.getOrgId());
        Integer orgLevel = null;
        if(organDROResponseDTO.getData() != null){
            orgLevel = organDROResponseDTO.getData().getLevel();
        }

        if (Objects.equals(orgLevel, GlobalConsts.LEVEL_3)) {
            companyId = loginStaff.getCompanyId();
        }
        List<KVDict<?>> list = Lists.newArrayList();
        boolean isContainsSys = false;
        logger.debug("listStaffByDeptIdAndTextAndStatus入参text【{}】,companyId【{}】,status 【2】 orgLevel【{}】", text, companyId, orgLevel);

        StaffSimpleQueryDIO query = new StaffSimpleQueryDIO();
        if(companyId != null){
            query.setCompanyIds(Lists.newArrayList(companyId));
        }
        query.setKeyword(text);
        query.setStatus(Optional.ofNullable(status).orElse(GlobalConsts.YES));
        ResponseDTO<List<StaffDRO>> staffResponseDTO = staffListRemoteService.listStaffBySimpleQueryDIO(query);
        if (staffResponseDTO.isSuccess() && CollectionUtils.isNotEmpty(staffResponseDTO.getData())) {
            staffResponseDTO.getData().forEach((item) -> {
                String statusName = Objects.equals(item.getStatus(), GlobalConsts.NO) ? "(离职)" : "";
                String staffName = item.getRealName() + statusName;
                list.add(KVDict.builder().value(item.getStaffId()).text(staffName).ext1(MobileUtil.formatHideTel(item.getMobile())).build());
            });

            //是否包含系统
            isContainsSys = staffResponseDTO.getData().stream()
                    .anyMatch(e -> Objects.equals(e.getStaffId(), GlobalConsts.NO));
            logger.debug("是否包含系统 isContainsSys[{}]", isContainsSys);
        }

        if (StringUtils.isNotBlank(text) && !isContainsSys) {
            //大小写转换
            String newText = text.toLowerCase();
            boolean isPinYing = "xitong".contains(newText);
            boolean isXitong = "系统".contains(text);
            if (isPinYing || isXitong) {
                list.add(KVDict.builder().value(GlobalConsts.NO).text("系统").ext1("******").build());
            }
        }
        return ResultDTO.success(list);
    }

    /**
     * 查询工程师列表
     * @return
     */
    @GetMapping(value = "master/list")
    public ResultDTO masterList(@RequestParam(value = "companyId", required = false) Integer companyId,
                                @RequestParam(value = "manageCompanyId", required = false) Integer manageCompanyId,
                                @RequestParam(value = "gridId", required = false) Integer gridId,
                                @RequestParam(value = "cityId", required = false) Integer cityId,
                                @RequestParam(value = "plat") Integer plat,
                                @RequestParam(value = "text") String text) {
//        if (!NumberUtil.isNullOrZero(manageCompanyId) && (Objects.equals(GlobalConsts.PLAT_MARK_SAAS, plat))) {
//            companyId = manageCompanyId;
//        }

        //ThinkEngineerDIO thinkEngineerDIO = new ThinkEngineerDIO();
        ThinkEngineerQuery thinkEngineerDIO = new ThinkEngineerQuery();
        //thinkEngineerDIO.setText(text);
        thinkEngineerDIO.setKeyword(text);
        //thinkEngineerDIO.setDeptId(getDeptId());
        thinkEngineerDIO.setPlat(plat);
//        if (Objects.nonNull(companyId)){
//            thinkEngineerDIO.setCompanyId(companyId);
//        }
        thinkEngineerDIO.setCityId(cityId);

//        if (Objects.nonNull(gridId)){
//            thinkEngineerDIO.setGridId(gridId);
//        }
        logger.debug("通过权限、平台联想工程师数据入参:[{}]", JSON.toJSONString(thinkEngineerDIO));
        ResponseDTO<List<ThinkEngineerDRO>> listResponseDTO = engineerBasicListRemoteService.listThinkEngineerQuery(thinkEngineerDIO);
        logger.debug("通过权限、平台联想工程师数据出参:[{}]", JSON.toJSONString(listResponseDTO));
        if (!listResponseDTO.isSuccess() || listResponseDTO.getData() == null) {
            return ResultDTO.fail("list is empty");
        }
        List<KVDict<?>> list = Lists.newArrayListWithExpectedSize(listResponseDTO.getData().size());
        listResponseDTO.getData().forEach(item -> {
            // TODO lujia 已离职状态需要 常量定义
            String statusName = Objects.equals(item.getOaStatus(), 3) ? "(离职)" : "";
            String masterName = item.getRealName() + statusName;
            list.add(KVDict.builder().value(item.getEngineerId()).text(masterName).ext1(MobileUtil.formatHideTel(item.getMobile())).build());
        });
        return ResultDTO.success(list);
    }

    /**
     * 查询工程师信息
     * @return
     */
    @GetMapping(value = "master/detail")
    public ResultDTO masterDetail(@RequestParam(value = "masterId") Integer masterId) {
        //2020年06月02日18:31:22 更新接口
        logger.debug("masterDetail#getEngineerDetailById 入参 [{}]",masterId);
        ResponseDTO<ForeignEngineerDetailInfoDRO> cacheEngineerByEngineerId = engineerListRemoteService.getEngineerDetailById(masterId);
        logger.debug("masterDetail#getEngineerDetailById 出参 [{}]",JSON.toJSONString(cacheEngineerByEngineerId));
        if (!cacheEngineerByEngineerId.isSuccess() || cacheEngineerByEngineerId.getData() == null) {
            return ResultDTO.fail("not found master");
        }
        return ResultDTO.success(cacheEngineerByEngineerId.getData());
    }

    /**
     * 查询工程师列表
     * @return
     */
    @GetMapping(value = "find/master/list")
    public ResultDTO findMasterList(@RequestParam(value = "manageCompanyId") Integer manageCompanyId,
                                    @RequestParam(value = "plat") Integer plat,
                                    @RequestParam(value = "text", required = false) String text) {
        logger.debug("findMasterList#listEngineerBySpCommonIdAndPlatAndKeyword 入参 [{}] [{}] [{}]",manageCompanyId,plat,text);
        ResponseDTO<List<ForeignEngineerDetailInfoDRO>> listResponseDTO = engineerListRemoteService.listEngineerBySpCommonIdAndPlatAndKeyword(manageCompanyId, plat, text);
        logger.debug("findMasterList#listEngineerBySpCommonIdAndPlatAndKeyword 出参 [{}]",JSON.toJSONString(listResponseDTO));

        if (listResponseDTO.getData() == null) {
            return ResultDTO.fail("list is empty");
        }
        List<KVDict<?>> list = Lists.newArrayListWithExpectedSize(listResponseDTO.getData().size());
        listResponseDTO.getData().forEach(item -> {
            String statusName = Objects.equals(item.getOaStatus(), 3) ? "(离职)" : "";
            String masterName = item.getRealName() + statusName;
            list.add(KVDict.builder().value(item.getEngineerId()).text(masterName).ext1(MobileUtil.formatHideTel(item.getMobile())).build());
        });
        return ResultDTO.success(list);

    }

    /**
     * 查询工程师主管列表
     *
     * @return
     */
    @GetMapping(value = "master/supervisor/list")
    public ResultDTO findMasterList(@RequestParam(value = "plat") Integer plat,
                                    @RequestParam(value = "text", required = false) String text) {
        // EngineerOrSupervisorDRO engineerOrSupervisorDRO =
        // 判断是否为工程师主管 ResponseDTO<EngineerOrSupervisorDRO> engineerOrSupervisorDROResponseDTO =
        LoginStaff currentStaff = super.getCurrentStaff();
        logger.debug("findMasterList#getByStaffId 入参 [{}]", currentStaff.getStaffId());
        ResponseDTO<SupervisorDetailDRO> engineerOrSupervisorDROResponseDTO = engineerSupervisorListRemoteService.getByStaffId(currentStaff.getStaffId());
        logger.debug("findMasterList#getByStaffId 出参 [{}]", JSON.toJSONString(engineerOrSupervisorDROResponseDTO));
        SupervisorDetailDRO engineerOrSupervisorDRO = engineerOrSupervisorDROResponseDTO.getData();
        if (Objects.nonNull(engineerOrSupervisorDRO)) {
            logger.debug("findMasterList#getByKey 入参 [{}]", engineerOrSupervisorDRO.getSupervisorId());
            ResponseDTO<SupervisorDetailDRO> engineerSupervisorBaseDROResponseDTO = engineerSupervisorListRemoteService.getByKey(engineerOrSupervisorDRO.getSupervisorId());
            logger.debug("findMasterList#getByKey 出参 [{}]",JSON.toJSONString(engineerSupervisorBaseDROResponseDTO));
            SupervisorDetailDRO baseDROResponseDTOData = engineerSupervisorBaseDROResponseDTO.getData();
            if (Objects.nonNull(baseDROResponseDTOData)) {
                return ResultDTO.success(Lists.newArrayList(
                        KVDict.builder().value(baseDROResponseDTOData.getSupervisorId()).text(baseDROResponseDTOData.getSupervisorName()).ext1(MobileUtil.formatHideTel(baseDROResponseDTOData.getMobile())).build())
                );
            }
        }

        logger.debug("findMasterList#listSupOptionByValue 入参 [{}] [{}]",plat,text);
        SupervisorInfoQuery supervisorInfoQuery = new SupervisorInfoQuery();
        supervisorInfoQuery.setPlat(plat);
        supervisorInfoQuery.setKeyword(text);
        ResponseDTO<List<Option<Integer>>> listResponseDTO = engineerSupervisorListRemoteService.listSupOptionByValue(supervisorInfoQuery);
        logger.debug("indMasterList#listSupOptionByValue 出参 [{}]",JSON.toJSONString(listResponseDTO));
        if (listResponseDTO == null || CollectionUtils.isEmpty(listResponseDTO.getData())) {
            return ResultDTO.fail("list is empty");
        }

        List<KVDict<?>> list = Lists.newArrayListWithExpectedSize(listResponseDTO.getData().size());
        listResponseDTO.getData().forEach(item -> {
            list.add(KVDict.builder().value(item.getValue()).text(item.getLabel()).ext1("").build());
        });
        return ResultDTO.success(list);
    }
}
